﻿using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Helpers
{
    /// <summary>
    /// https://github.com/ExcelDataReader/ExcelDataReader
    /// </summary>
    public class ExcelHelper
    {
        public static DataSet ReadExcelAsDataSet(string filePath)
        {
            DataSet result = null;
            using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    result = reader.AsDataSet();
                }
            }
            return result;
        }

        public static DataTable ReadExcelAsDataTable(string filePath, string tableName = "sheet1")
        {
            DataTable result = ReadExcelAsDataSet(filePath).Tables[tableName];
            return result;
        }

        public static DataSet ReadCsvAsDataSet(string filePath)
        {
            DataSet result = null;
            using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                using (var reader = ExcelReaderFactory.CreateCsvReader(stream, new ExcelReaderConfiguration
                {
                    AutodetectSeparators = new char[] { ',', ';', '\t', '|', '#' }
                }))
                {
                    result = reader.AsDataSet();
                }
            }
            return result;
        }

        public static DataTable ReadCsvAsDataTable(string filePath)
        {
            DataTable result = ReadCsvAsDataSet(filePath).Tables["Table1"];
            return result;
        }

        public static string CreateCsvLine(params string[] arr)
        {
            if (arr?.Length > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in arr)
                {
                    sb.Append($"\"{item.Replace("\"", "\"\"")}\",");
                }
                return sb.ToString().TrimEnd(',');
            }
            else
                return null;
        }
    }
}
